package com.call.service;

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.call.Constants;
import com.call.data.MissCallData;

public class PhoneDialStateListener extends PhoneStateListener 
{
	private static final String TAG = PhoneDialStateListener.class.getSimpleName();
	private IMissCallAndPhoneNumberService bindService = null;
	private String ringPhoneNumber;
	private int lastStart = -1;
	public PhoneDialStateListener(IMissCallAndPhoneNumberService bindService) {
		super();
		this.bindService = bindService;
	}
	@Override
    public void onCallStateChanged(int state, String incomingNumber)
    {
        switch (state)
        {
            case TelephonyManager.CALL_STATE_RINGING:
            	Log.i(TAG, "phone number:" + incomingNumber);
            	try 
            	{
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	ringPhoneNumber = incomingNumber;
            	
                break;
            case TelephonyManager.CALL_STATE_IDLE:
            	if(lastStart == TelephonyManager.CALL_STATE_RINGING)
            	{
            		long now = System.currentTimeMillis();
                	try 
                	{
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
            		bindService.AddMissCallInfo(ringPhoneNumber, now);
            		Log.i(Constants.Tag, "Listener add miss call!");
            	}
                //Log.i(TAG, "IDLE");
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
               // Log.i(TAG, "OFFHOOK");
                break;
        }
        lastStart = state;
    }
}
